<template>
    <view class="page-register-index">
        <view class="mx-4">
            <!-- <view class="mb-2 text-center">
                <button
                    class="avatar"
                    hover-class="none"
                    open-type="chooseAvatar"
                    style="background-color: transparent"
                    @click="changeAvatar"
                    @chooseavatar="changeAvatar"
                >
                    <u-image :src="proxy.$util.getFullImage(form.avatar)" shape="circle" width="180rpx" height="180rpx" class="inline-block"></u-image>
                    <view class="text-xs c-grey9"> 点击上传头像 </view>
                </button>
            </view> -->
            <u-form ref="form1" label-width="160rpx">
                <u-form-item label="手机号">
                    <u-input v-model="form.phone" placeholder="请选择" v-if="form.phone" disabled />
                    <button @getphonenumber="getPhoneNumber" open-type="getPhoneNumber" v-else class="phone" size="mini" plain>
                        <text>点击授权获取手机号码</text>
                    </button>
                </u-form-item>
                <u-form-item label="昵称">
                    <input :value="form.nickname" placeholder="填写昵称" type="nickname" @input="e => form.nickname = e.detail.value"></input>
                </u-form-item>
                <!-- <u-form-item label="密码">
                    <u-input v-model="form.password" placeholder="请选择" />
                </u-form-item>
                <u-form-item label="确认密码">
                    <u-input v-model="form.password2" placeholder="请选择" />
                </u-form-item> -->
                <u-form-item label="活动城市" right-icon="arrow-right" v-if="isCity">
                    <u-input v-model="picker.cityName"  disabled placeholder="请选择" @click="refGetCity.init()"/>
                </u-form-item>
            </u-form>
            <template v-if="!pageParams.cardId">
                <view class="card">
                    <view class="price">￥{{card?.price}}</view>
                    <view class="day">{{card?.durationValue}}{{proxy.$util.setName(card?.durationType, optionData.durationType)}}</view>
                </view>
                <view class="tips">支付后会获得{{card.durationValue}}{{proxy.$util.setName(card.durationType, optionData.durationType)}}的会员，会员期内可以参加所有线下共读活动，加入读书会社群及使用平台所有功能。</view>
            </template>
            <view class="mt-[40rpx]">
                <u-checkbox-group>
                    <u-checkbox v-model="isAgree" label-size="26rpx" active-color="#67E5C2">
                        我同意并了解
                        <text class="c-cyan" @click.stop="refShowAgreement.init('user')">《用户协议》</text>、
                        <text class="c-cyan" @click.stop="refShowAgreement.init('privacy')">《隐私协议》</text>、
                        <text class="c-cyan" @click.stop="refShowAgreement.init('member')">《会员服务协议》</text>
                    </u-checkbox>
                </u-checkbox-group>
            </view>
            <view class="mt-[40rpx]">
                <u-button class="btn-cyan-gradient" shape="circle" :loading="btnLoading" @click="submitForm"> 立即注册 </u-button>
            </view>
        </view>
        <u-picker v-model="picker.regionShow" :params="picker.regionParams" mode="region" @confirm="getRegion"></u-picker>
        <get-city ref="refGetCity" @confirm="getRegion" />
        <show-agreement ref="refShowAgreement" @confirm="confirmAgreement" />
    </view>
</template>
<script setup lang="ts">
import { uploadImg } from '@/static/js/upload';
import getCity from './components/getCity.vue';
import showAgreement from '@/components/showAgreement/index.vue';
let refGetCity = ref();
let refShowAgreement = ref();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
import { useAppStore } from '@/stores/app'
let appStore = useAppStore();
import { useOptionData } from '@/stores/optionData';
let optionDataStore = useOptionData();
let pageParams = reactive({cardId: null});
const form = reactive({
    avatar: null,
    nickname: null,
    phone: '',
    mobileCode: '',
    password: 'Bookclub88888888',
    password2: 'Bookclub88888888',
    cardId: '', //
    adcode: '', // 如果有inviterUserId,或者体验卡cardId，就不显示
    inviterUserId: '', //用户分享的用户id
    type: 1,
});
let isAgree = ref(false);
let btnLoading = ref(false);
let picker = reactive({
    regionParams:{
        province: true,
	    city: true,
        area: false
    },
    regionShow: false,
    cityName: null,
    cityId: null,
});
let card = ref({
    durationValue: null,
    durationType: null,
});
let isCity = ref(true);
let optionData = reactive({
    durationType: [],
});

const getInitData = async () => {
    optionData.durationType = await optionDataStore.getDictList('duration_type');
    getCard();
}
const getCard = () => {
    proxy.$http('get', '/admin/membershipCards/1', {}, (data,msg) => {
        card.value = data;
    });
}
const getRegion = val => {
    picker.cityId = val.adcode;
    picker.cityName = val.name;
    form.adcode = val.adcode;
};
const confirmAgreement = (val) => {
    isAgree.value = true;
}
const changeAvatar = (e:any) => {
    let val = e.detail.avatarUrl;
    if(val){
        uploadImg('/admin/sys-file/upload', val).then(res => {
            form.avatar = res.url;
        });
    }
};
const getPhoneNumber = (e) => {
    console.log(e);
    if(e.detail.code){
        appStore.getPhoneNumber(e.detail.code).then(res => {
            form.phone = res;
        })
    }
}
const verifyForm = () => {
    if(!proxy.$verify.mobile(form.phone, '请授权获取手机号')){
        return false;
    }
    if(!proxy.$verify.null(form.nickname, '请输入昵称')){
        return false;
    }
    // if(!proxy.$verify.null(form.avatar, '请上传头像')){
    //     return false;
    // }
    if(!isAgree.value){
        uni.$u.toast('请勾选并同意并了解《用户协议》、《隐私协议》、《会员服务协议》');
        return false;
    }
    return true;
};
const submitForm = () => {
    if(!verifyForm()){
        return;
    }
    appStore.handleRegister(proxy.$util.getParam(form)).then(data => {
        console.log(pageParams.cardId, data);
        if(!pageParams.cardId){
            console.log('去支付',data);
            toPay(data.userId);
        }else{
            wxLogin();
        }
        
    });
};
const toPay = (userId:any) => {
	uni.login({
		success: response => {
            console.log(response);
            let cardId = '1'
            if(form.card){
                cardId = form.card;
            }
            let strBody = {type: 'new', userId: userId};
            let params  = {
                body: JSON.stringify(strBody), // new新开卡，xu续费
                userId: userId,
                relationshipId: cardId,
                code: response.code
            };
            appStore.wechatPay(params).then(res => {
                uni.requestPayment({
                    provider: 'wxpay',
                    ...JSON.parse(res),
                    success: successRres => {
                        // 注册并支付后，开始登录成功并跳转
                        wxLogin();
                    }, 
                    error: err => {
                    
                    }
                })
            })			
		},
		fail: () => {
			reject()
		}
	})
    
};
const wxLogin = () => {
    appStore.wxLogin().then(res => {
        proxy.$util.gotoPage('/pages/home/index');
    });
};
onLoad((e) => {
    uni.login({
        provider: 'weixin',
        success: loginRes => {
            form.mobileCode = loginRes.code;
        }
    });
    pageParams = e;
    if(e.cardId){
        form.cardId = e.cardId;
        isCity.value = false;
    }else{
        isCity.value = true;
        if(e.inviterUserId){
            form.inviterUserId = e.inviterUserId;
            isCity = false;
        }else{
            isCity = true;
        }
    }
    
    
});
onShow(() => {
    getInitData();
})
</script>
<style>
page{height:100%;}
</style>